import axios from "axios";
import JSONP from "jsonp";
let BASE_URL = '';

const instance = axios.create({
    timeout: 120000,               // 请求超时时间
});
instance.defaults.withCredentials = true;
// status < 500 不会抛错误
instance.defaults.validateStatus = status => {
    return status < 400;
};
// 设置请求token
instance.interceptors.request.use(config => {
    let token = localStorage.getItem('clienttoken');
    if (window.token) {
        if (window.token == token) {
            token && (config.headers['Authorization'] = 'Bearer ' + token);
        }
    } else {
        token && (config.headers['Authorization'] = 'Bearer ' + token);
    }
    return config;
});

// 接口错误拦截
instance.interceptors.response.use(res => {
    return res.data;
}, err => {
    if (err.response && err.response.status == 401){
        localStorage.removeItem('clienttoken');
    }
    return Promise.reject(err);
});

function chekcResult(response) {
    if (response){
        if (response.err) {
            throw new Error(response.err);
        } else {
            return response.result;
        }
    }
    return null;
}

async function get(url, params) {
    url = BASE_URL + url;
    let r = await instance.get(url, { params });
    return chekcResult(r);
}

async function post(url, data) {
    url = BASE_URL + url;
    let r = await instance.post(url, data);
    return chekcResult(r);
}

async function put(url, data) {
    url = BASE_URL + url;
    let r = await instance.put(url, data);
    return chekcResult(r);
}

async function del(url) {
    url = BASE_URL + url;
    let r = await instance.delete(url);
    return chekcResult(r);
}

async function jsonp(url, params) {
    return new Promise((resolve, reject) => {
        let qs = [];
        for (let p in params) {
            qs.push(`${p}=${encodeURIComponent(params[p])}`);
        }
        url = qs.length > 0 ? (`${url}?${qs.join('&')}`) : url;
        JSONP(url, {}, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

export default {
    get,
    put,
    post,
    del,
    jsonp
};